<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ANR 日志分析工具</title>
  <!-- Element Plus CSS -->
  <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
      background-color: #f5f7fa;
    }

    .header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 0 20px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .header h1 {
      margin: 0;
      display: flex;
      align-items: center;
      font-size: 24px;
      font-weight: 600;
    }

    .main-content {
      padding: 20px;
      max-width: 800px;
      margin: 0 auto;
    }

    .analysis-card {
      margin-bottom: 20px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .analysis-form {
      max-width: 600px;
    }

    .result-card {
      margin-bottom: 20px;
    }

    .success-content {
      margin-top: 20px;
    }

    .files-section {
      margin-top: 20px;
    }

    .file-tag {
      margin: 5px 5px 5px 0;
    }

    .error-content {
      margin-top: 20px;
    }

    .progress-card {
      margin-bottom: 20px;
    }

    .progress-text {
      text-align: center;
      margin-top: 10px;
      color: #666;
    }
  </style>
</head>

<body>
  <div id="app">
    <!-- 头部 -->
    <div class="header">
      <h1>
        <span>📱</span>
        ANR 日志分析工具
      </h1>
      <div class="status">
        <span id="serviceStatus">检查中...</span>
      </div>
    </div>

    <!-- 主内容 -->
    <div class="main-content">
      <!-- 分析表单 -->
      <div class="analysis-card"
        style="background: white; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); padding: 20px;">
        <div class="card-header" style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #ebeef5;">
          <span style="font-size: 18px; font-weight: 600;">设备日志分析</span>
          <button id="refreshBtn"
            style="background: #409eff; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">
            🔄 刷新状态
          </button>
        </div>

        <form id="analysisForm" class="analysis-form">
          <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600;">设备SN</label>
            <input type="text" id="deviceSn" placeholder="请输入设备SN号"
              style="width: 100%; padding: 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
            <div id="deviceSnError" style="color: #f56c6c; font-size: 12px; margin-top: 4px;"></div>
          </div>

          <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600;">手机号</label>
            <input type="text" id="phone" value="18650630979"
              style="width: 100%; padding: 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
          </div>

          <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600;">用户名</label>
            <input type="text" id="username" value="fangxiang01"
              style="width: 100%; padding: 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
          </div>

          <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 600;">密码</label>
            <input type="password" id="password" value="1234589y.F"
              style="width: 100%; padding: 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;">
          </div>

          <div>
            <button type="button" id="startBtn"
              style="background: #409eff; color: white; border: none; padding: 12px 24px; border-radius: 4px; cursor: pointer; font-size: 16px; margin-right: 10px;">
              🔍 开始分析
            </button>
            <button type="button" id="resetBtn"
              style="background: #909399; color: white; border: none; padding: 12px 24px; border-radius: 4px; cursor: pointer; font-size: 16px;">
              🔄 重置
            </button>
          </div>
        </form>
      </div>

      <!-- 分析结果 -->
      <div id="resultCard" class="result-card"
        style="display: none; background: white; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); padding: 20px;">
        <div class="card-header" style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #ebeef5;">
          <span style="font-size: 18px; font-weight: 600;">分析结果</span>
          <span id="resultStatus" style="padding: 4px 8px; border-radius: 4px; font-size: 12px;"></span>
        </div>
        <div id="resultContent"></div>
      </div>

      <!-- 进度显示 -->
      <div id="progressCard" class="progress-card"
        style="display: none; background: white; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); padding: 20px;">
        <div style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #ebeef5;">
          <span style="font-size: 18px; font-weight: 600;">分析进度</span>
        </div>
        <div style="background: #f5f7fa; height: 8px; border-radius: 4px; overflow: hidden;">
          <div id="progressBar" style="background: #409eff; height: 100%; width: 0%; transition: width 0.3s;"></div>
        </div>
        <p id="progressText" class="progress-text"></p>
      </div>
    </div>
  </div>

  <!-- Axios -->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  <script>
    // 全局变量
    let analyzing = false;
    let progressInterval = null;

    // DOM元素
    const deviceSnInput = document.getElementById('deviceSn');
    const phoneInput = document.getElementById('phone');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const startBtn = document.getElementById('startBtn');
    const resetBtn = document.getElementById('resetBtn');
    const refreshBtn = document.getElementById('refreshBtn');
    const serviceStatus = document.getElementById('serviceStatus');
    const resultCard = document.getElementById('resultCard');
    const resultContent = document.getElementById('resultContent');
    const resultStatus = document.getElementById('resultStatus');
    const progressCard = document.getElementById('progressCard');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const deviceSnError = document.getElementById('deviceSnError');

    // 初始化
    document.addEventListener('DOMContentLoaded', function () {
      refreshStatus();
      bindEvents();
    });

    // 绑定事件
    function bindEvents() {
      startBtn.addEventListener('click', startAnalysis);
      resetBtn.addEventListener('click', resetForm);
      refreshBtn.addEventListener('click', refreshStatus);
    }

    // 刷新状态
    async function refreshStatus() {
      try {
        const response = await axios.get('/api/analysis/status');
        serviceStatus.textContent = response.data;
        serviceStatus.style.color = response.data === '服务已初始化，浏览器已启动' ? '#67c23a' : '#e6a23c';
      } catch (error) {
        serviceStatus.textContent = '服务连接失败';
        serviceStatus.style.color = '#f56c6c';
      }
    }

    // 验证表单
    function validateForm() {
      const deviceSn = deviceSnInput.value.trim();
      const phone = phoneInput.value.trim();
      const username = usernameInput.value.trim();
      const password = passwordInput.value.trim();

      // 清空错误信息
      deviceSnError.textContent = '';

      if (!deviceSn) {
        deviceSnError.textContent = '请输入设备SN';
        return false;
      }

      // SN格式验证
      const snPattern = /^(7\d{17}|(A010|A020)\d{14})$/;
      if (!snPattern.test(deviceSn)) {
        deviceSnError.textContent = 'SN格式不正确，应为：以7开头的18位数字 或 以A010/A020开头的17位字符';
        return false;
      }

      if (!phone) {
        alert('请输入手机号');
        return false;
      }

      if (!username) {
        alert('请输入用户名');
        return false;
      }

      if (!password) {
        alert('请输入密码');
        return false;
      }

      return true;
    }

    // 开始分析
    async function startAnalysis() {
      if (!validateForm()) {
        return;
      }

      analyzing = true;
      updateUI();

      // 显示进度
      progressCard.style.display = 'block';
      resultCard.style.display = 'none';

      // 模拟进度更新
      let progress = 0;
      progressInterval = setInterval(() => {
        if (progress < 90) {
          progress += Math.random() * 10;
          updateProgress(progress);
        }
      }, 1000);

      try {
        const formData = {
          deviceSn: deviceSnInput.value.trim(),
          phone: phoneInput.value.trim(),
          username: usernameInput.value.trim(),
          password: passwordInput.value.trim()
        };

        const response = await axios.post('/api/analysis/device', formData);

        clearInterval(progressInterval);
        updateProgress(100);

        if (response.data.success) {
          showResult(response.data, true);
          alert('设备日志分析成功！');
        } else {
          showResult(response.data, false);
          alert('分析失败：' + response.data.message);
        }
      } catch (error) {
        clearInterval(progressInterval);
        updateProgress(100);

        let errorData = { message: '分析过程中发生错误' };
        if (error.response && error.response.data) {
          errorData = error.response.data;
        }

        showResult(errorData, false);
        alert('分析过程中发生错误');
      } finally {
        analyzing = false;
        updateUI();
      }
    }

    // 更新进度
    function updateProgress(percent) {
      progressBar.style.width = percent + '%';

      if (percent < 20) {
        progressText.textContent = '初始化浏览器...';
      } else if (percent < 40) {
        progressText.textContent = '登录系统...';
      } else if (percent < 60) {
        progressText.textContent = '下载日志文件...';
      } else if (percent < 80) {
        progressText.textContent = '解压并分析文件...';
      } else if (percent < 100) {
        progressText.textContent = '生成分析报告...';
      } else {
        progressText.textContent = '分析完成！';
      }
    }

    // 显示结果
    function showResult(data, success) {
      progressCard.style.display = 'none';
      resultCard.style.display = 'block';

      if (success) {
        resultStatus.textContent = '成功';
        resultStatus.style.background = '#67c23a';
        resultStatus.style.color = 'white';

        resultContent.innerHTML = `
                    <div style="margin-bottom: 15px;">
                        <strong>设备SN：</strong>${data.deviceSn || ''}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>分析时间：</strong>${data.analysisTime ? new Date(data.analysisTime).toLocaleString('zh-CN') : ''}
                    </div>
                    <div style="margin-bottom: 15px;">
                        <strong>输出目录：</strong>${data.outputDirectory || ''}
                    </div>
                    ${data.generatedFiles && data.generatedFiles.length > 0 ? `
                        <div>
                            <strong>生成的文件：</strong>
                            <div style="margin-top: 10px;">
                                ${data.generatedFiles.map(file => `<span style="background: #f0f9ff; color: #409eff; padding: 4px 8px; border-radius: 4px; margin-right: 8px; margin-bottom: 8px; display: inline-block;">${file}</span>`).join('')}
                            </div>
                        </div>
                    ` : ''}
                `;
      } else {
        resultStatus.textContent = '失败';
        resultStatus.style.background = '#f56c6c';
        resultStatus.style.color = 'white';

        resultContent.innerHTML = `
                    <div style="background: #fef0f0; border: 1px solid #fbc4c4; color: #f56c6c; padding: 15px; border-radius: 4px;">
                        <strong>错误信息：</strong>${data.message || '未知错误'}
                        ${data.errorDetails ? `<br><strong>详细信息：</strong>${data.errorDetails}` : ''}
                    </div>
                `;
      }
    }

    // 重置表单
    function resetForm() {
      deviceSnInput.value = '';
      phoneInput.value = '18650630979';
      usernameInput.value = 'fangxiang01';
      passwordInput.value = '1234589y.F';
      deviceSnError.textContent = '';
      resultCard.style.display = 'none';
      progressCard.style.display = 'none';
    }

    // 更新UI状态
    function updateUI() {
      const disabled = analyzing;
      deviceSnInput.disabled = disabled;
      phoneInput.disabled = disabled;
      usernameInput.disabled = disabled;
      passwordInput.disabled = disabled;
      startBtn.disabled = disabled;
      resetBtn.disabled = disabled;

      startBtn.textContent = analyzing ? '分析中...' : '🔍 开始分析';
    }
  </script>
</body>

</html>